<template>
  <div>
    <a-form-model
      layout="horizontal"
      :model="caseDetail"
      v-bind="{
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      }"
    >
      <a-form-model-item label="案例标题">
        <a-input v-model.trim="caseDetail.name" />
      </a-form-model-item>
      <a-form-model-item label="人物">
        <a-select
          style="width: 120px"
          placeholder="必选"
          :options="characterList"
          @change="onCharacterChange"
          v-model="caseDetail.characterId"
          :field-names="{ value: 'id', lable: 'name' }"
        >
        </a-select>
        <br />
        <a-button
          type="primary"
          @click="$router.push(`/web/characters/list`)"
          icon="plus"
          >添加人物</a-button
        >
      </a-form-model-item>
      <a-form-model-item label="分类">
        <a-checkbox-group
          :defaultValue="caseDetail.classifyArr"
          :options="classifyOptions"
          @change="onClassifyChange"
          v-model="caseDetail.classifyArr"
        />
        <br v-if="classifyOptions.length > 1" />
        <a-button icon="plus" type="primary" @click="toggleClassifyModal">
          创建分类
        </a-button>
      </a-form-model-item>
      <a-modal
        centered
        title="提交分类"
        v-model="classifyModal"
        @ok="submitClassification"
        @cancel="toggleClassifyModal"
      >
        <a-input v-model="name" placeholder="分类名"></a-input>
      </a-modal>
      <a-form-model-item label="封面图片" prop="name">
        <a-upload
          name="avatar"
          :headers="headers"
          accept="image/*"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :action="uploadUrl"
          :before-upload="beforeUpload"
          @change="handleChange"
        >
          <img v-if="caseDetail.cover" :src="caseDetail.cover" alt="avatar" />
          <div v-else>
            <a-icon :type="photoLoading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item label="案例描述">
        <a-textarea
          v-model.trim="caseDetail.sketch"
          :auto-size="{ minRows: 1, maxRows: 4 }"
        />
      </a-form-model-item>
      <a-form-model-item label="案例内容">
        <wangEditor
          v-model="caseDetail.content"
          :disabled="wangEditorDisable"
        ></wangEditor>
      </a-form-model-item>
    </a-form-model>
    <div class="actions">
      <a-button type="primary" @click="showModal">
        提交
      </a-button>
      <a-button type="primary" @click="back"> 返回 </a-button>
    </div>
    <a-modal
      centered
      title="提交"
      v-model="visible"
      @ok="submit"
      @cancel="cancel"
    >
      <p>确认提交？</p>
    </a-modal>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import wangEditor from '@/pages/components/wangEditor/index.vue';
import { getCharacterListApi } from '@/services/webApi/character';
import {
  getCaseByIdApi,
  editCaseApi,
  addCaseApi,
  addClassifyApi,
  getClassifyListApi,
} from '@/services/webApi/case';
import { UPLOAD } from '@/services/webApi/api';
// import { getCaseByIdAdminApi } from '@/services/superAdmin';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  components: { wangEditor },
  data() {
    return {
      caseId: 0,
      projectId: 0,
      caseDetail: {},
      uploadUrl: '',
      headers: {},
      photoLoading: false,
      visible: false,
      wangEditorDisable: false,
      desc: '',
      classifyOptions: [],
      classifyModal: false,
      name: '', // 分类名
      characterId: '',
      characterList: [],
    };
  },
  mounted() {
    this.uploadUrl = UPLOAD;
    this.headers['authorization'] = JSON.parse(
      localStorage.getItem('user')
    ).token;
    this.caseId = this.$route.params.id;
    this.getClassifyList();
    this.getCharacterList();
    if (this.caseId == 0) {
      return;
    }
    if (this.user.type === '2') {
      this.admin();
    } else {
      this.superAdmin();
      this.wangEditorDisable = true;
    }
  },
  computed: {
    ...mapGetters('account', ['user']),
  },
  methods: {
    back() {
      window.history.go(-1);
    },
    getCharacterList() {
      getCharacterListApi().then((res) => {
        res.data.forEach((ele) => {
          this.characterList.push({ label: ele.name, value: ele.id });
        });
      });
    },
    onCharacterChange(value) {
      this.characterId = value;
    },
    onClassifyChange(checkedValues) {
      this.$set(this.caseDetail, 'classifyArr', checkedValues);
    },
    getClassifyList() {
      getClassifyListApi().then((res) => {
        res.data.rows.forEach((ele) => {
          this.classifyOptions.push({ label: ele.name, value: ele.id });
        });
      });
    },
    submitClassification() {
      if (!this.name) {
        this.$message.error('不能为空');
        return;
      }
      addClassifyApi({ name: this.name })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('添加成功');
            this.classifyOptions.push({
              label: res.data.name,
              value: res.data.id,
            });
            this.classifyModal = false;
          }
        })
        .catch((err) => {
          this.$message.error(err.msg);
        });
    },
    toggleClassifyModal() {
      this.classifyModal = !this.classifyModal;
    },
    async superAdmin() {
      // this.caseId = this.$route.params.id;
      // let res = await getCaseByIdAdminApi({
      //   id: this.caseId,
      // });
      // this.caseDetail = res.data;
    },
    async admin() {
      let res = await getCaseByIdApi({
        id: this.caseId,
      });
      this.caseDetail = res.data;
      this.characterId = res.data.characterId;
      this.$set(
        this.caseDetail,
        'classifyArr',
        res.data.w_classifies.map((v) => v.id)
      );
    },
    showModal() {
      this.visible = true;
    },
    submit() {
      if (!this.caseDetail.cover) {
        this.$message.error('请选择封面');
        this.visible = false;
        return;
      }
      if (!this.caseDetail.name) {
        this.$message.error('标题不能为空');
        this.visible = false;
        return;
      }
      if (!this.caseDetail.sketch) {
        this.$message.error('描述不能为空');
        this.visible = false;
        return;
      }
      if (!this.caseDetail.content) {
        this.$message.error('内容不能为空');
        this.visible = false;
        return;
      }
      if (this.caseId != 0) {
        editCaseApi({ ...this.caseDetail, characterId: this.characterId })
          .then((res) => {
            this.$message.success(res.msg);
            setTimeout(() => {
              window.history.go(-1);
            }, 500);
          })
          .catch((err) => {
            this.$message.error(err.msg);
          });
      } else {
        addCaseApi(this.caseDetail)
          .then((res) => {
            this.$message.success(res.msg);
            setTimeout(() => {
              window.history.go(-1);
            }, 500);
          })
          .catch((err) => {
            this.$message.error(err.msg);
          });
      }
    },
    cancel() {
      this.visible = false;
    },
    // 图片上传
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.photoLoading = true;
        return;
      }
      if (info.file.status === 'done') {
        this.caseDetail.cover = info.file.response.path;

        getBase64(info.file.originFileObj, (imageUrl) => {
          this.img = imageUrl;
          this.photoLoading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/bmp' ||
        file.type === 'image/gif' ||
        file.type === 'image/webp';
      if (!isJpgOrPng) {
        this.$message.error('只能上传图片');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
.upload {
  width: 5rem;
  height: 5rem;
  border: solid;
}
img {
  width: 10rem;
  height: 10rem;
}
.actions {
  text-align: center;
  padding-right: 5rem;
  .ant-btn {
    margin-right: 10px;
  }
}
::v-deep .ant-cascader-picker {
  width: 110px;
}
</style>
